package com.sec.etech.employeesync.confighandler;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sec.etech.employeesync.entity.OrgEmployeeZProfessionalTitle;
import com.sec.etech.employeesync.mapper.OrgEmployeeZProfessionalTitleMapper;
import com.sec.etech.employeesync.util.ConfigTableHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Optional;

@Component
@Slf4j
public class ProfessionalTitleConfigHandler implements ConfigTableHandler<OrgEmployeeZProfessionalTitle> {

    @Resource
    private OrgEmployeeZProfessionalTitleMapper professionalTitleMapper;

    @Override
    public Long getOrCreateConfigId(String... params) {
        String name = params[0];
        OrgEmployeeZProfessionalTitle professionalTitle = getEntityByName(name);
        if (professionalTitle == null) {
            professionalTitle = new OrgEmployeeZProfessionalTitle();
            professionalTitle.setCode(generateNextCode());
            professionalTitle.setName(name);
            professionalTitle.setActive(1);
            insertEntity(professionalTitle);
            log.info("新增职称配置:name={}", name);
        }
        return professionalTitle.getProfessionalTitleId();
    }

    @Override
    public OrgEmployeeZProfessionalTitle getEntityByName(String name) {
        return professionalTitleMapper.selectOne(Wrappers.<OrgEmployeeZProfessionalTitle>lambdaQuery()
                .eq(OrgEmployeeZProfessionalTitle::getName, name));
    }

    @Override
    public String generateNextCode() {
        OrgEmployeeZProfessionalTitle politics = professionalTitleMapper.selectOne(Wrappers.<OrgEmployeeZProfessionalTitle>lambdaQuery()
                .orderByDesc(OrgEmployeeZProfessionalTitle::getCode)
                .last("limit 1"));

        String lastCode = Optional.ofNullable(politics)
                .map(OrgEmployeeZProfessionalTitle::getCode)
                .orElse("0");

        return generateNextCode(lastCode);
    }

    @Override
    public void insertEntity(OrgEmployeeZProfessionalTitle entity) {
        professionalTitleMapper.insert(entity);
    }
}
